
var helpers = require('../ParseHelpers');

module.exports = EntityParser;

function EntityParser() {}

EntityParser.ForEntityName = 'HATCH';

EntityParser.prototype.parseEntity = function(scanner, curr) {
    var entity, endAngle;
    entity = { type: curr.value };
    curr = scanner.next();
    while(curr !== 'EOF') {
        if(curr.code === 0) break;

        switch(curr.code) {
            case 72: // X coordinate of point
                entity.vertices = parseVertices(entity.vertices,scanner);
                if(entity.vertices.length == 2){
                    entity.vertices.push({
                        "x": (entity.vertices[0].x + entity.vertices[1].x) / 2,
                        "y": (entity.vertices[0].y + entity.vertices[1].y) / 2,
                        "t": "c",
                        "r": 4.5,
                        "startAngle": - 7*Math.PI / 32,
                        "endAngle": 25*Math.PI /32,
                        "z": null
                    })
                }
                break;
            default: // ignored attribute
                helpers.checkCommonEntityProperties(entity, curr);
                break;
        }
        curr = scanner.next();
    }
    return entity;
};

function parseVertices(vertices, scanner) {

    if(typeof vertices == 'undefined'){
        vertices = []
    }
    var point;
    var curr = scanner.lastReadGroup;
    
    switch(curr.value) {
        case 1:
            curr = scanner.next()
            if(curr.code == 73){
                curr = scanner.next()
            }
            if(curr.code == 93){
                curr = scanner.next()
            }
            point = helpers.parsePoint(scanner)
            point.t = 'p'
            if(!(vertices.length > 0 && vertices[vertices.length - 1].t == 'p')){
                vertices.push(point)
            }
            curr = scanner.next();
            point = helpers.parsePoint(scanner)
            point.t = 'p'
            vertices.push(point)
        break;
        case 2:
            curr = scanner.next()
            point = helpers.parsePoint(scanner)
            point.t = 'c'
            point.r = scanner.next().value
            point.startAngle = Math.PI / 180 * scanner.next().value
            point.endAngle = Math.PI / 180 * scanner.next().value
            vertices.push(point)
        break;
    }
    return vertices;
};